package kk.service.impl;

import kk.dao.BookDao;
import kk.dao.impl.BookDaoImpl;
import kk.domain.Book;
import kk.domain.PageBean;
import kk.service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService {
    private BookDao bookDao=new BookDaoImpl();
    @Override
    public void addBook(Book book) {
        bookDao.addBook(book);
    }

    @Override
    public void deleteBookById(Integer id) {
       bookDao.deleteBookById(id);
    }

    @Override
    public void updateBook(Book book) {
        bookDao.updateBook(book);
    }

    @Override
    public Book queryBookById(Integer id) {
        Book book = bookDao.queryBookById(id);
        return book;
    }

    @Override
    public List<Book> queryBooks() {
        List<Book> books = bookDao.queryBooks();
        return books;
    }

    @Override
    public PageBean<Book> page(int currentPage, int pageSize) {
        PageBean<Book> pageBean=new PageBean();
        //查询出totalCount
        int totalCount=bookDao.getTotalCount();
        pageBean.setTotalCount(totalCount);


        pageBean.setPageSize(pageSize);
        int totalPage=totalCount%pageSize==0?(totalCount/pageSize):(totalCount/pageSize+1);
        pageBean.setTotalPage(totalPage);

        //如果当前页大于总页码
        if(currentPage>totalPage){
            currentPage=totalPage;
        }else if(currentPage<1){
            currentPage=1;
        }
        pageBean.setCurrentPage(currentPage);


        int begin=(currentPage-1)*pageSize;
        List<Book> list = bookDao.queryBooksForPage(begin,pageSize);
        pageBean.setList(list);

        return pageBean;
    }

    @Override
    public PageBean<Book> pageByPrice(int currentPage, int pageSize, int min, int max) {
        PageBean<Book> pageBean=new PageBean();
        //查询出totalCount
        int totalCount=bookDao.getTotalCountByPrice(min,max);
        pageBean.setTotalCount(totalCount);


        pageBean.setPageSize(pageSize);
        int totalPage=totalCount%pageSize==0?(totalCount/pageSize):(totalCount/pageSize+1);
        pageBean.setTotalPage(totalPage);

        //如果当前页大于总页码
        if(currentPage>totalPage){
            currentPage=totalPage;
        }else if(currentPage<1){
            currentPage=1;
        }
        pageBean.setCurrentPage(currentPage);


        int begin=(currentPage-1)*pageSize;
        List<Book> list = bookDao.queryBooksForPageByPrice(begin,pageSize,min,max);
        pageBean.setList(list);

        return pageBean;
    }
}
